package com.buddy.summary.code.java8;

import org.apache.poi.ss.formula.functions.T;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FilterApple {

    private static final List<Apple> inventory = Arrays.asList(
            new Apple(1, "green"),
            new Apple(2, "red"),
            new Apple(2, "green"));

    //1.筛选绿苹果
    public static List<Apple> filterGreenApples(List<Apple> inventory) {
        List<Apple> result = new ArrayList<>();
        for (Apple apple : inventory) {
            if ("green".equals(apple.getColor())) {
                result.add(apple);
            }
        }
        return result;
    }

    //2.把颜色作为参数
    public static List<Apple> filterAppleByColor(List<Apple> inventory, String color) {
        List<Apple> result = new ArrayList<>();
        for (Apple apple : inventory) {
            if (color.equals(apple.getColor())) {
                result.add(apple);
            }
        }
        return result;
    }

    //3.对每个属性做筛选


    //4.行为参数化
    public static List<Apple> filterApple(List<Apple> inventory, ApplePredicate applePredicate) {
        List<Apple> result = new ArrayList<>();
        for (Apple apple : inventory) {
            if (applePredicate.test(apple)) {
                result.add(apple);
            }
        }
        return result;
    }

    //5.使用匿名类
    @Test
    public void test5() {
        filterApple(inventory, new AppleColorPredicate() {
            @Override
            public boolean test(Apple apple) {
                return super.test(apple);
            }
        });
    }

    //6.使用Lambda表达式
    public void test6() {
        filterApple(inventory, (Apple apple) -> "red".equals(apple.getColor()));
    }

    //7.将List类型抽象化
    public static <T> List<T> filter(List<T> list,Predicate<T> predicate){
        List<T> result = new ArrayList<>();
        for (T t: list){
            if (predicate.test(t)){
                result.add(t);
            }
        }
        return result;
    }



}
